package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegisterVo;
import com.atguigu.gulimall.member.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo registerVo) {
        MemberEntity memberEntity = new MemberEntity();
        String userName = registerVo.getUserName();
        String phone = registerVo.getPhone();
        // 设置会员等级id
        MemberLevelEntity memberLevelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        // 校验手机号和验证码是否唯一
        checkUsername(userName);
        checkPhone(phone);
        // 赋值
        memberEntity.setUsername(userName);
        memberEntity.setMobile(phone);
        memberEntity.setNickname(userName);
        // 对密码进行盐值加密 md5
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(registerVo.getPassword());
        memberEntity.setPassword(encodePassword);
        // 保存 插入数据库
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUsername(String username) {
        //   判断用户名是否在数据库已经存在
        Integer usernameCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (usernameCount > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkPhone(String phone) {
        Integer phoneCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (phoneCount > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        // 根据账号查询数据库的数据
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", memberLoginVo.getLoginacct()).or().eq("mobile", memberLoginVo.getLoginacct()));
        if (Objects.nonNull(memberEntity)) {
            String passwordVo = memberLoginVo.getPassword();
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(passwordVo, passwordDb);
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public MemberEntity oAuthLogin(SocialUserVo socialUserVo) {
        // 根据uid到数据库中查找会员信息
        String uid = socialUserVo.getUid();
        // 判断当前用户是否已经登录过系统
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (Objects.nonNull(memberEntity)) {
            // 已注册  通过Id 更新数据
            MemberEntity member = new MemberEntity();
            member.setId(memberEntity.getId());
            member.setAccessToken(socialUserVo.getAccessToken());
            member.setExpiresIn(String.valueOf(socialUserVo.getExpiresIn()));
            // 更新
            this.baseMapper.updateById(memberEntity);
            return baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        } else {
            // 进行注册
            MemberEntity member = new MemberEntity();
            // 不管是否查询成功 都要继续向下执行
            try {
                // 查询当前社交用户的社交账户的信息(例如：昵称、性别等)
                Map<String, String> queryMaps = new HashMap<>(2);
                queryMaps.put("access_token", socialUserVo.getAccessToken());
                queryMaps.put("uid", socialUserVo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(0), queryMaps);
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 返回成功 转换成json
                    String res = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(res);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    // 其他信息查询
                    member.setNickname(name);
                    member.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
            }
            member.setAccessToken(socialUserVo.getAccessToken());
            member.setExpiresIn(String.valueOf(socialUserVo.getExpiresIn()));
            member.setSocialUid(socialUserVo.getUid());
            // 新增
            baseMapper.insert(member);
            return member;
        }
    }
}